<template>
  <div class="right-main">
    <div class="tob-bar">
      <el-breadcrumb separator=">">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/system/userList' }">员工管理</el-breadcrumb-item>
        <el-breadcrumb-item>新增</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="mainContainer addUserPage">
      <div class="user-file-image">
        <el-image style="width: 120px; height: 120px;border-radius:50%;overflow:hidden;">
          <!-- 默认图片 -->
          <div slot="error" class="image-slot" @click="centerDialogVisible = true">
            <img width="120" height="120" v-if="user.avatar" :src="user.avatar" />
            <img
              height="120"
              width="120"
              v-if="!user.avatar"
              src="@/assets/images/default-user-img.png"
            />
          </div>
        </el-image>
        <p>
          <el-button class="upload-img-btn" type="text" @click="centerDialogVisible = true">
            <i class="el-icon-upload2"></i> 上传照片
          </el-button>
        </p>
      </div>
      <!-- 表单 -->
      <div class="customform shebaoform">
        <el-form
          :inline="true"
          :model="user"
          :rules="rules"
          label-width="130px"
          label-position="left"
          ref="user"
        >
          <div class="user-title">基本信息</div>
          <div class="el-form--inline">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="user.name" placeholder></el-input>
            </el-form-item>
            <el-form-item label="身份证号码" prop="idCard">
              <el-input v-model="user.idCard" placeholder></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sexual">
              <el-checkbox-group v-model="user.sexual" @change="bindCheckBox">
                <el-checkbox name="sexual" label="男" v-model="user.male" checked=""></el-checkbox>
                <el-checkbox name="sexual" label="女" v-model="user.female"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </div>
          <div class="el-form--inline">
            <el-form-item label="邮箱" prop="email">
              <el-input type="email" v-model="user.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="telephone">
              <el-input v-model="user.telephone" type="number"></el-input>
            </el-form-item>
            <RoleSelect label-name="角色" :p_value.sync="user.roles"></RoleSelect>
          </div>
          <div class="user-title2">
            <span>基本信息</span>
          </div>
          <div class="el-form--inline">
            <DeptSelect label-name="所属部门" :p_value.sync="user.depid"></DeptSelect>
            <el-form-item label="岗位" prop="jobPosition">
              <el-input v-model="user.jobPosition" placeholder></el-input>
            </el-form-item>
            <UserSelect label-name="上级"></UserSelect>
          </div>
          <div class="el-form--inline">
            <el-form-item label="在职状态" prop="status">
              <el-select v-model="user.status" filterable>
                <el-option label="在职" value="1"></el-option>
                <el-option label="离职" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="入职时间" prop="entryDate">
              <el-date-picker
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                v-model="user.entryDate"
                type="date"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
            <!--<el-form-item label="离职时间" prop="value11">-->
            <!--<el-date-picker v-model="Form.value11" type="date" placeholder="选择日期"></el-date-picker>-->
            <!--</el-form-item>-->
          </div>
        </el-form>
      </div>
      <div class="page-form-btn">
        <el-button @click="back">取消</el-button>
        <el-button type="primary" @click="save('user')">保存</el-button>
      </div>
      <!-- 表单结束 -->
    </div>
    <!-- 上传头像 -->
    <el-dialog
      title="上传头像"
      :visible.sync="centerDialogVisible"
      class="custom-dialog userImageUpload"
      width="480px"
      center
    >
      <div class="user-img-upload">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            height="220"
            width="220"
            v-if="user.avatar"
            :src="user.avatar"
            class="user-page-avatar"
          />
          <img
            height="220"
            width="220"
            v-if="!user.avatar"
            src="@/assets/images/default-user-img.png"
            class="user-page-avatar"
          />
          <span v-else>
            <i class="el-icon-plus avatar-uploader-icon"></i>
            <p>选择图片</p>
            <p>只支持JPG/PNG/GIF，GIF文件</p>
            <p>建议尺寸240x240</p>
          </span>
        </el-upload>
        <br>
        <p>点击图片上传</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 上传头像结束 -->
  </div>
</template>

<script>
import Http from "../../libs/http.js";
import DeptSelect from "../../components/DeptSelect";
import RoleSelect from "../../components/RoleSelect";
import UserSelect from "../../components/UserSelect";

export default {
  name: "addUser",
  components: {
    DeptSelect,
    RoleSelect,
    UserSelect
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      //定义规则
      let reg = /^1[345789]\d{9}$/;
      if (value === "") {
        callback(new Error("手机号不能为空"));
      } else if (value != "" && reg.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的手机号"));
      }
    };
    const validateIdCard = (rule, value, callback) => {
      let regId = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/;
      if (value === "") {
        callback(new Error("身份证号不能为空"));
      } else if (!regId.test(value)) {
        callback(new Error("请输入正确的身份证号"));
      }
      else{
        callback();
      }
    };
    const validateEmail = (rule, value, callback) => {
      let regEmail=/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (value === "") {
        callback(new Error("邮箱不能为空"));
      } else if (!regEmail.test(value)) {
        callback(new Error("请输入正确的邮箱"));
      }
      else{
        callback();
      }
    };
    return {
      centerDialogVisible: false,
      imageUrl: "",
      // 表单
      user: {
        avatar: "",
        roles: [],
        sex: "",
        name: "",
        jobPosition: "",
        entryDate: "",
        sexual: [
          {
            female: true,
            male: false
          }
        ],
        depid: "",
        loginName: "",
        password: "",
        idCard: "",
        email: "",
        telephone: "",
        parentId: "",
        status: ""
      },
      // 必填项目
      rules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        idCard: [
          { required: true, validator: validateIdCard, trigger: "blur" }
        ],
        sexual: [
          {
            type: "array",
            required: true,
            message: "请选择性别",
            trigger: "change"
          }
        ],
        email: [{ required: true, validator:validateEmail, trigger: "blur" }],
        telephone: [
          { required: true, validator: validatePhone, trigger: "blur" }
        ],
        // value5: [
        //   { required: true, message: "请选择用户角色", trigger: "change" }
        // ],
        depid: [
          { required: true, message: "请选择所属部门", trigger: "change" }
        ],
        jobPosition: [
          { required: true, message: "请输入岗位", trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "请选择上级", trigger: "change" }
        ],
        status: [
          { required: true, message: "请选择在职状态", trigger: "change" }
        ],
        entryDate: [
          {
            type: "string",
            required: true,
            message: "请选择入职时间",
            trigger: "change"
          }
        ]
        // value11: [
        //   {
        //     type: "date",
        //     required: true,
        //     message: "请选择离职时间",
        //     trigger: "change"
        //   }
        // ]
      },
      uploadUrl: process.env.BASE_API + "/user/upload"
    };
  },
  methods: {
    // 图片上传
    handleAvatarSuccess(res, file) {
      this.user.avatar = res.url;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("只支持JPG/PNG/GIF文件!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 单选
    bindCheckBox(value) {
      this.user.sexual = [];
      this.user.sexual.push(value[1]);
    },
    // 保存
    save(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.user.sex == this.user.sexual.male ? 0 : 1;
          Http.api.post("user", this.user).then(res => {
            this.$router.push({ path: "/system/userlist" });
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    back() {
      this.$router.go(-1);
    }
  }
};
</script>
